<script>
import { getCityByKeyword } from "@/api/publish";
import { HTTP_REQUEST_URL } from '@/config/app';
export default {
  props: ["value", "is_all"],
  data() {
    return {
      isSearch: false,
      searchLoading: false,
      show: false,
      showAnimate: false,
      currentData: [],
      searchData: [],
      currentColumnIndex: 0,
      fullCityList: [],
      cityList: [],
      columnList: [[], [], []],
      historyData: [],
      keyword: "",
    };
  },
  created() {
    //TODO: 请求全部城市列表,并缓存
    this.getList();

    this.getHistory();
  },
  watch: {
    show(newVal) {
      if (newVal) {
        // if (!this.value) this.currentData = [];
        // this.currentColumnIndex = 0
        this.$emit('open', this.show)
        if (this.value) {
          // this.getCityByValue();
        }
        setTimeout(() => {
          this.showAnimate = true;
        }, 10);
      }
    },
  },
  methods: {
    async getCityByValue() {
      const res = await getCityByKeyword({ city_id: this.value });
      const item = res.data.data.data[0];
      // console.log(item);

      this.currentData = [
        {
          label: item.country.name,
          label_ru: item.country.name_ru,
          value: item.country.id,
        },
        {
          label: item.province.name,
          label_ru: item.province.name_ru,
          value: item.province.id,
        },
        {
          label: item.city.name,
          label_ru: item.city.name_ru,
          value: item.city.id,
        },
      ];
      // console.log(this.currentData);
      // console.log(this.fullCityList);

      this.columnList[0] = this.fullCityList;
      this.columnList[1] = this.fullCityList.find(
        (fitem) => fitem.value == item.city.country
      ).children;
      this.columnList[2] = this.columnList[1].find(
        (fitem) => fitem.value == item.province.id
      ).children;
      this.cityList = this.columnList[2];
      // console.log(this.columnList)
      this.currentColumnIndex = 2;
    },
    async getCityByKeyword() {
      if (!this.keyword) {
        this.toast(this.$t('请输入城市名称'));
        return;
      }
      this.isSearch = true;
      this.currentData = [];
      this.currentColumnIndex = 0;

      this.searchLoading = true;
      const res = await getCityByKeyword({ keyword: this.keyword });
      this.searchLoading = false;
      this.searchData = res.data.data.data;
    },
    getList() {
      uni.request({
        url: `${HTTP_REQUEST_URL}/basic/getSelectCityList?is_port=true&pid=0&lang=zh`, //仅为示例，并非真实接口地址。
        data: {
          is_all: this.is_all ? 1 : 0
        },
        header: {},
        success: (res) => {
          // console.log(res.data.data);
          this.fullCityList = res.data.data;
          this.cityList = this.fullCityList;
          this.columnList[0] = this.fullCityList;
          //如果传递了值，则直接设置当前数据
          if (this.value) {
            //TODO: 根据传递的城市查询出国家/省份/城市 复现
            // this.getCityByValue();
          }
        },
      });
    },
    close() {
      this.cityList = this.fullCityList;
      this.currentData = [];
      this.showAnimate = false;
      this.isSearch = false;
      this.$emit('openStateChange', false)
      setTimeout(() => {
        this.show = false;
      }, 300);
    },
    addCity(item) {
      console.log(item);

      if (!this.currentData) {
        this.currentData = [];
      }
      this.currentData[this.currentColumnIndex] = item;
      this.currentColumnIndex++;

      if (this.currentColumnIndex == 1 || this.currentColumnIndex == 2) {
        // console.log(item.children);
        // item.children.unshift({
        //   label: "不限",
        //   label_ru: "不限",
        // });
      }


      this.cityList = item.children;
      this.columnList[this.currentColumnIndex] = item.children;

      console.log(JSON.parse(JSON.stringify(item)), this.currentColumnIndex);


      //选择了不限
      if (item.value == -1 && this.currentColumnIndex == 1) {
        this.currentData = [
          { label: item.label, label_ru: item.label_ru, value: item.value },
          {
            label: item.children[0].label,
            label_ru: item.children[0].label_ru,
            value: item.children[0].value,
          },
          {
            label: item.children[0].children[0].label,
            label_ru: item.children[0].children[0].label_ru,
            value: item.children[0].children[0].value,
          },
        ];
        this.currentColumnIndex = 0;
        this.confirm();
      }

      if (!item.children) {
        this.currentColumnIndex = 0;
        this.confirm();
      }
      this.$nextTick(() => {
        this.$refs.cityPickerList.scrollTop = 0;
      });
    },
    addCity2(item) {
      this.currentData = [
        {
          label: item.country.name,
          label_ru: item.country.name_ru,
          value: item.country.id,
        },
        {
          label: item.province.name,
          label_ru: item.province.name_ru,
          value: item.province.id,
        },
        {
          label: item.city.name,
          label_ru: item.city.name_ru,
          value: item.city.id,
        },
      ];
      // console.log(this.currentData);
      this.confirm();
    },
    confirm(item) {
      const data =
        item ||
        this.currentData.map((item) => {
          return {
            label: item.label,
            value: item.value,
            label_ru: item.label_ru,
          };
        });
      this.saveHistory(data);
      this.$emit("change", {
        column1: data[0],
        column2: data[1],
        column3: data[2],
      });
      this.close();
    },
    removeCity(index) {
      this.currentData.splice(index + 1, this.currentData.length - index);
      this.currentColumnIndex = index;
      console.log(this.columnList);

      this.cityList = this.columnList[index];

      this.$nextTick(() => {
        this.$refs.cityPickerList.scrollTop = 0;
      });
    },
    clearHistory() {
      uni.showModal({
        title: "提示",
        content: "确定要清空历史选择吗？",
        confirmText: this.$t("确定"),
        cancelText: this.$t("取消"),
        success: (res) => {
          if (res.confirm) {
            this.historyData = [];
            uni.removeStorageSync("cityHistory");
          }
        },
      });
    },

    saveHistory(item) {
      if (this.historyData.some((hItem) => hItem[2].value === item[2].value))
        return;
      this.historyData.unshift(item);
      // 保持最新的5条记录，删除旧的
      this.historyData = this.historyData.filter((item, index) => index < 5);
      uni.setStorageSync("cityHistory", this.historyData);
    },
    getHistory() {
      this.historyData = uni.getStorageSync("cityHistory") || [];
    },
  },
};
</script>
<template>
  <div class="city">
    <div class="btn" @click="show = true; $emit('openStateChange', true)">
      <slot></slot>
    </div>

    <div class="city-picker-msak" v-if="show" :class="{ 'opacity-100': showAnimate }" @click="close"></div>
    <div class="city-picker-container" v-if="show" :class="{ 'opacity-100': showAnimate }">
      <div class="city-picker-content h-full">
        <div class="center font-bold" style="position: relative">
          城市选择
          <div class="close" style="position: absolute; right: 30rpx; top: 0rpx" @click="close">
            <image src="/static/icon/close.png" mode="aspectFill" class="w-25 h-25"></image>
          </div>
        </div>

        <div class="search flex-shrink-0">
          <input type="text" :disabled="searchLoading" class="fz28 w-full h-full" placeholder="请输入城市名称"
            v-model="keyword" />
          <div class="flex flex-shrink-0">
            <div class="reset-btn mr-20" v-if="searchData.length > 0 && !searchLoading" @click="
              searchData = [];
            keyword = '';
            cityList = fullCityList;
            isSearch = false;
            ">
              重置
            </div>
            <div class="search-btn flex" @click="getCityByKeyword()">
              <image src="/static/loading.gif " v-if="searchLoading" mode="aspectFill" class="w-50 h-50">
              </image>
              <text v-else>搜索</text>
            </div>
          </div>
        </div>

        <div v-if="!searchLoading" style="
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
          ">
          <template v-if="!isSearch">
            <div class="pl-30 pr-30 pt-30">
              <div class="history-title between">
                历史选择
                <div class="fz24 text-gray-500" @click="clearHistory">
                  清空历史
                </div>
              </div>
              <div class="tags">
                <div class="tag" @click="confirm(item)" v-for="item in historyData">
                  {{
                    item[0].value == -1
                      ? "不限"
                      : item.map((item) => item.label).join("-")
                  }}
                </div>
              </div>
            </div>

            <div class="pl-30 pr-30 pt-30" v-if="currentData.length > 0">
              <div class="history-title">当前选择</div>
              <div class="tags flex tags2">
                <template v-for="(item, index) in currentData">
                  <div class="tag active" :class="{ active2: index === currentColumnIndex }" @click="removeCity(index)">
                    {{ item.label }}
                  </div>
                  <div class="line2" v-if="index < currentData.length - 1"></div>
                </template>
              </div>
            </div>

            <div class="line"></div>
            <div class="font-bold mt-20 fz28 pl-30">请选择</div>

            <div class="city-picker-list" ref="cityPickerList">
              <div class="city-picker-item" @click="addCity(item)" v-for="item in cityList" v-if="item.label != '请选择'">
                {{ item.label }}
              </div>
            </div>
          </template>

          <template v-else>
            <div class="font-bold mt-20 fz28 pl-30">查询结果</div>
            <div class="city-picker-list">
              <div class="city-picker-item" @click="addCity2(item)" v-for="item in searchData">
                <div class="fz28 font-bold mb-10">
                  {{ item.city.name }}
                </div>
                <div class="fz22 text-gray-500">
                  {{ item.city.mergename }}
                </div>
              </div>
              <div class="fz22 text-gray-500 center mt-50" v-if="searchData.length === 0">
                没有找到相关城市，请重新输入
              </div>
            </div>
          </template>
        </div>
        <div v-else class="center flex-col text-gray-500 fz26" style="padding-top: 200rpx">
          <image src="/static/loading.gif" mode="aspectFill" class="w-150 h-150"></image>
          正在加载中...
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
	@import '@/assets/appScss.scss';
.flex-shrink-0 {
  flex-shrink: 0;
}

.opacity-100 {
  opacity: 1 !important;
  transform: translate3d(0, 0, 0) !important;
}

.tags2 {
  .tag {
    font-size: 26rpx;
  }
}

.line2 {
  width: 10rpx;
  background-color: #ff7b2e;
  height: 2rpx;
}

.active {
  border: 1rpx solid #ff7b2e;
  color: #ff7b2e !important;
  background-color: #fff6f1 !important;
}

.active2 {
  background-color: #ffe1d0 !important;
}

.history-title {
  font-size: 28rpx;
  color: #3d3d3d;
  font-weight: bold;
  margin-bottom: 16rpx;
}

.search {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15rpx 30rpx;
  background-color: #f5f5f5;
  margin-top: 20rpx;
}

.search-btn {
  color: #fff;
  background-color: #3d3d3d;
  width: 150rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10rpx;
  font-size: 26rpx;
  box-sizing: border-box;
}

.reset-btn {
  width: 150rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10rpx;
  font-size: 26rpx;
  background-color: #fff;
  box-sizing: border-box;
}

.city-picker-list {
  display: flex;
  flex-direction: column;
  gap: 0rpx;
  margin: 20rpx 0;
  overflow-y: auto;
  margin-bottom: 0;
  height: 100%;
}

.city-picker-item {
  color: #3d3d3d;
  padding: 15px 30rpx;
  font-size: 28rpx;

  &:active {
    background-color: #f5f5f5;
  }
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin: 20rpx 0;
}

.tag {
  color: #666;
  padding: 10rpx 20rpx;
  background: #f5f5f5;
  font-size: 24rpx;
  border-radius: 10rpx;
}

.line {
  width: 100%;
  height: 1rpx;
  background: #ddd;
  margin: 20rpx 0;
}

.city-picker-msak {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 99;
  opacity: 0;
  transition: 0.3s ease;
}

.city-picker-container {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  display: flex;
  align-items: flex-end;
  transform: translate3d(0, 100%, 0);
  transition: 0.3s ease;
  height: 80vh;
}

.city-picker-content {
  width: 100%;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx 0;
  display: flex;
  flex-direction: column;
  padding-bottom: 0;
  overflow: hidden;
}

.city {}
</style>
